package com.cuoyi.coupon.mall.utils;

import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author chengzhang
 * 2021/6/28 14:35
 */
public class PageUtil {


    /**
     * 对集合进行分页
     */
    public static <T> List<T> getPageList(Integer pageNum, Integer pageSize, List<T> t) {
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 10;
        }
        if (CollectionUtils.isEmpty(t)) {
            return t;
        }
        //记录总数
        int count = t.size();
        //页数
        int pageCount;

        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        //开始索引
        int fromIndex;
        //结束索引
        int toIndex;

        if (pageNum > pageCount) {
            pageNum = pageCount;
        }

        if (!pageNum.equals(pageCount)) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }
        t = t.subList(fromIndex, toIndex);
        return t;
    }
}
